﻿using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.Text;

namespace Utils.Weixin.Pay.Result
{
    public class TransactionResult
    {
        public string TransactionId { get; set; }

        public decimal Amount { get; set; }

        public string Mchid { get; set; }

        public string Attach { get; set; }

        public string TradeType { get; set; }

        public DateTime? SuccessTime { get; set; }

        public string OpenId { get; set; }

        public string OutTradeNo { get; set; }

        public string AppID { get; set; }

        public string BankType { get; set; }

        /// <summary>
        /// SUCCESS：支付成功
        /// REFUND：转入退款
        /// NOTPAY：未支付
        /// CLOSED：已关闭
        /// REVOKED：已撤销（付款码支付）
        /// USERPAYING：用户支付中（付款码支付）
        /// PAYERROR：支付失败(其他原因，如银行返回失败)
        /// </summary>
        public string TradeState { get; set; }

        public string TradeStateDesc { get; set; }

        internal static TransactionResult Create(JObject jobj)
        {
            return new TransactionResult()
            {
                Amount = ((int)jobj["amount"]["total"]) / 100m,
                AppID = (jobj["AppID"] ?? jobj["appid"] ?? jobj["sub_appid"] ?? jobj["sp_appid"]).ToString(),
                OutTradeNo = jobj["out_trade_no"].ToString(),
                TransactionId = jobj["transaction_id"]?.ToString(),
                Attach = jobj["attach"]?.ToString(),
                Mchid = (jobj["mchid"]?? jobj["sub_mchid"] ?? jobj["sp_mchid"]).ToString(),
                TradeState = jobj["trade_state"].ToString(),
                BankType = jobj["bank_type"]?.ToString(),
                SuccessTime = jobj["success_time"]?.Value<DateTime>(),
                OpenId = jobj["payer"]?["openid"]?.ToString(),
                TradeType = jobj["trade_type"]?.ToString(),
                TradeStateDesc = jobj["trade_state_desc"]?.ToString()
            };
        }

    }
}
